package com.mw.job.controller;

import com.mw.job.bean.AppProperties;
import com.mw.job.bean.DisruptorProperties;
import com.mw.job.bean.ZkProperties;
import com.mw.job.disruptor.DisruptorProducer;
import com.xiaoleilu.hutool.util.NetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
public class IndexController {

	private Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	DisruptorProperties disruptorProperties;

	@Autowired
	DisruptorProducer disruptorProducer;

	@Autowired
	AppProperties appProperties;

	@Autowired
	ZkProperties zkProperties;

	@Autowired
	ServerProperties serverProperties;

	@RequestMapping("/")
	public String index(HttpServletRequest request, Model model){

		log.info("index 首页");


		model.addAttribute("prop",disruptorProperties);

		boolean proStatus = disruptorProducer.isStop();

		String loopTime = "";
		Boolean flag = disruptorProperties.getCornTask();
		if (flag){
			loopTime = disruptorProperties.getLoopTime()+"	(corn表达式)";
		}else {
			loopTime = disruptorProperties.getLoopTime()+"	(ms)";
		}

		String ip = NetUtil.getLocalhostStr();
		serverProperties.getPort();
		String nodeInfo = ip+":"+serverProperties.getPort()+" 节点信息";

		model.addAttribute("proStatus",!proStatus);
		model.addAttribute("app",appProperties);
		model.addAttribute("loopTime",loopTime);
		model.addAttribute("nodeInfo",nodeInfo);
		model.addAttribute("zk",zkProperties);
		model.addAttribute("serverTime",System.currentTimeMillis());

		return "index";
	}


	@RequestMapping("/startProducer")
	public String startProducer(HttpServletRequest request, Model model){

		log.info("启动生产者……");

		disruptorProducer.setStop(false);

		return "redirect:/";
	}



	@RequestMapping("/stopProducer")
	public String stopProducer(HttpServletRequest request, Model model){

		log.info("停止生产者……");

		disruptorProducer.setStop(true);

		return "redirect:/";
	}


	/**
	 * 改变生产者状态
	 * @return
	 */
	@RequestMapping("/trigger")
	@ResponseBody
	public Boolean trigger(){

		log.info("trigger 生产者状态接口被调用...");

		boolean isStop = disruptorProducer.isStop();

		disruptorProducer.setStop(!isStop);

		return isStop;
	}


	@RequestMapping("/state")
	@ResponseBody
	public Boolean state(){

		log.info("生产者状态接口被调用...");

		return disruptorProducer.isStop();

	}

}



















